package com.zqweb.gulimall.order.interceptor;

import com.zqweb.common.constant.AuthServerConstant;
import com.zqweb.common.vo.MemberUserInfoVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class OrderLoginInterceptor implements HandlerInterceptor {
    // 存储登陆的用户信息的threadLocal
    public static ThreadLocal<MemberUserInfoVo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match1 = matcher.match("/order/order/getOrderEntity/**", uri);// 定时性操作，和用户是否登陆没有什么关系
        boolean match2 = matcher.match("/payed/notify", uri);// 支付宝支付成功后的异步通知，也无需登陆
        // match1或 match2对应的请求，都给放行
        if(match1 || match2){
            return true;
        }

        HttpSession session = request.getSession();
        MemberUserInfoVo memberUserInfoVo = (MemberUserInfoVo)session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        if(memberUserInfoVo != null){
            threadLocal.set(memberUserInfoVo);
            return true;// 放行请求
        }else{
            response.setContentType("text/html;Charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("<script>alert('请先进行登陆，再来继续操作！');location.href='http://auth.gulimall.com/login.html'</script>");

            session.setAttribute("errMsg","请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            // Caused by: java.lang.IllegalStateException: Cannot create a session after the response has been committed

            return false;// 拦截请求，不能继续访问相应的资源
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
